#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Last modified: 

"""docstring
"""

__revision__ = '0.1'

import urllib,urllib2,cookielib
from BeautifulSoup import BeautifulSoup
import time,random

msg = ['很遗憾的告诉你，这不是真的',\
        '你知道的，我发这些只是为了测试',\
        '测试灌水机而已，淡定。。',\
        'Sorry..it is only a test,so easy..'\
        ]

def login():
    '''登录脚本'''
    print 'Trying to login...'

    cookie = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie),urllib2.HTTPHandler)
    urllib2.install_opener(opener)

    postdata = urllib.urlencode({'email':'',\
                                  'password':'',\
                                  'origURL':'http://www.renren.com/home',\
                                  'domain':'renren.com'\
                                  })
#    print postdata
    req = urllib2.Request(url = 'http://www.renren.com/PLogin.do',\
                         data = postdata
                         )
    req.addheaders = [('User-Agent','Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0'),\
            ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),\
            ('Accept-Encoding','gzip,deflate'),\
            ('Referer','http://renren.com/Login.do')]
#    req.add_header('User-Agent','Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0')



    print '....login form submitted'
    result = urllib2.urlopen(req)
    if result.geturl() == 'http://www.renren.com/home':
        print '...login succeed!'
    else :
        print 'login failed...'

body = {'categoryId':'0','blogControl':'99','editBlogControl':'99','passwordProtected':'0','passWord':''}
url_post = 'http://blog.renren.com/NewEntry.do'


def post():
    '''发贴函数'''
    post = urllib2.urlopen(url_post).read()
    soupPost = BeautifulSoup(post)
    postid = soupPost.find('input',{'id':'postFormId'})
    formId = str(postid['value'])
    body['postFormId'] = formId
#    body['requestToken'] = formId




    data = urllib2.urlopen('http://www.qiushibaike.com').read()
    soup = BeautifulSoup(data)
    contents = soup.findAll('div','qiushi_body article ')
    for num in range(len(contents)):
        para=contents[num].p
#        print type(str(para))
        post_data = str(para) + '<br /><a href="http://www.qiushibaike.com">版权所有-糗事百科</a><br />'
        post_data += '<hr /><b>' + random.choice(msg) + '</b>' + '<br />Powered by linuxfish'
#        print post_data
        title = '糗事-%d' %(num+21)   #帖子计数
        body['title'] = title
        body['body'] = str(post_data)
#        print urllib.urlencode(body)
        post_req = urllib2.urlopen(url_post,urllib.urlencode(body))
        print '%d article posted!' %(num+21)
        time.sleep(random.randint(6,11))



if __name__ == '__main__':
    login()
    post()



